package com.android.antelopeapp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.antelopeapp.R;
import com.android.antelopeapp.constant.ApiConfig;
import com.android.antelopeapp.constant.MsgConfig;
import com.android.antelopeapp.network.ApiManager;
import com.android.antelopeapp.network.GsonRequest;
import com.android.antelopeapp.network.NetworkManager;
import com.android.antelopeapp.utils.NetworkUtils;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lyhw.model.Article;
import com.lyhw.model.TBItem;
import com.lyhw.model.beanwraper.WraperFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class ReArticleDetailActivity extends BaseActivity {
    private WebView mWebView;
    private String mReArticleId;
    private EditText mCommentEdit;
    private View mShareBox, mLikeBox, mSendBox;

    public static void launch(BaseActivity activity, View transitionView) {
        Intent intent = new Intent(activity, ReArticleDetailActivity.class);
        /*
        ActivityOptionsCompat options =
                ActivityOptionsCompat.makeSceneTransitionAnimation(
                        activity, transitionView,null);
        ActivityCompat.startActivity(activity, intent, options.toBundle());
         */
        activity.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReArticleId = getIntent().getStringExtra(ApiConfig.RA_ID);
        mCommentEdit = (EditText) this.findViewById(R.id.article_comment_edittext);
        mShareBox = this.findViewById(R.id.share_box);
        mLikeBox = this.findViewById(R.id.like_box);
        mSendBox = this.findViewById(R.id.send_box);
        mWebView = (WebView) this.findViewById(R.id.article_content);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //String sumary="<html><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8'><style type='text/css'> h1 {color: red}p {color: blue}</style></head><body><h1>VaiVai</h1><p>欢迎使用外外</p></body></html>";
        //mWebView.loadDataWithBaseURL(null, sumary, "text/html", "UTF-8", null);
        //mWebView.getSettings().setJavaScriptEnabled(true);
        initEditText();
        initBtns();
        initWebView();
        startNetwork();
    }

    private int parseItem(String url){
        if(url.contains("taobao.com") || url.contains("tmall.com")){
            return 1;
        }
        return -1;
    }

    private void initWebView() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //todo 解析url
                if (parseItem(url)==1) {
                    if(!NetworkUtils.isNetworkConnected(getApplicationContext())){
                        //ReArticleDetailActivity.this.sendToastMsg(MsgConfig.NETWORK_FAILED);
                    }else {
                        //解析淘宝链接
                        url = ApiConfig.REQUEST_TAE_ITEM_INFO + "?link="+url;
                        //ReArticleDetailActivity.this.toast(url);
                        GsonRequest<WraperFactory.TBItemWraper> grequest = new GsonRequest<>(url,
                                WraperFactory.TBItemWraper.class,
                                null,
                                new Response.Listener<WraperFactory.TBItemWraper>() {
                                    @Override
                                    public void onResponse(WraperFactory.TBItemWraper response) {
                                        try {
                                            TBItem data = response.getData().get(0);
                                            ReArticleDetailActivity.this.showItemDetail(data.getTitle(), data.getUid(), data.getSource());
                                        }catch (Exception e){
                                            ReArticleDetailActivity.this.sendToastMsg(MsgConfig.GET_ITEMS_FAILURE);
                                            Log.d(MsgConfig.GET_ITEMS_FAILURE,e.getMessage());
                                            Log.getStackTraceString(e);
                                        }
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        ReArticleDetailActivity.this.sendToastMsg(MsgConfig.GET_ITEMS_FAILURE);
                                        Log.d(MsgConfig.GET_ITEMS_FAILURE,error.getMessage());
                                    }
                                });
                        NetworkManager.getInstance(ReArticleDetailActivity.this).getRequestQueue().add(grequest);
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
        });
    }

    private void startNetwork() {
        if (mReArticleId == null) {
            //todo 如果文章id获取失败如何解决
            Toast.makeText(this, "文章id获取失败!", Toast.LENGTH_SHORT);
            return;
        }
        if(!NetworkUtils.isNetworkConnected(getApplicationContext())){
            sendToastMsg(MsgConfig.NETWORK_FAILED);
        }else{
            String url = ApiConfig.REQUEST_ARTICLE_DETAIL+mReArticleId+"/";
            //设置html头部以及图片大小样式
            final String preHtml = "<html><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8'>" +
                    "<style>img{display: inline; height: auto; max-width: 100%;}</style>" +
                    "</head><body>";
            final String tailHtml = "</body></html>";

            GsonRequest<WraperFactory.ArticleWraper> gsonRequest = new GsonRequest<WraperFactory.ArticleWraper>(
                    Request.Method.GET,
                    url,
                    WraperFactory.ArticleWraper.class, null,
                    new Response.Listener<WraperFactory.ArticleWraper>() {
                        @Override
                        public void onResponse(WraperFactory.ArticleWraper response) {
                            List<Article> list = response.getData();
                            if(list != null && list.size()>0) {
                                mWebView.loadDataWithBaseURL(ApiConfig.SERVER_HOME, preHtml +list.get(0).getContent() + tailHtml, "text/html", "UTF-8", "");
                            }else{
                                //todo 容错处理 网络连接出错如何解决
                                mWebView.loadData("网络连接出错", "text/html", "utf-8");
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //todo 容错处理 网络连接出错如何解决
                            mWebView.loadData(error.toString(), "text/html", "utf-8");
                        }
                    }
            ){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map= new HashMap<>();
                    map.put(ApiConfig.RA_ID,mReArticleId);
                    return map;
                }
            };
            NetworkManager.getInstance(this.getApplicationContext()).getRequestQueue().add(gsonRequest);
        }
    }

    /**
     * 设置评论控件
     * 点击评论时隐藏分享、收藏按钮，显示发送按钮
     */
    private void initEditText() {

        mCommentEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mShareBox.setVisibility(View.GONE);
                    mLikeBox.setVisibility(View.GONE);
                    mSendBox.setVisibility(View.VISIBLE);

                    mCommentEdit.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                } else {
                    mShareBox.setVisibility(View.VISIBLE);
                    mLikeBox.setVisibility(View.VISIBLE);
                    mSendBox.setVisibility(View.GONE);

                    mCommentEdit.setGravity(Gravity.CENTER);
                }
            }
        });
    }

    private void initBtns() {
        TextView share = (TextView) this.findViewById(R.id.article_share_btn);
        TextView like = (TextView) this.findViewById(R.id.article_like_btn);
        ImageButton send = (ImageButton) this.findViewById(R.id.article_comment_send_btn);
        share.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //todo 链接服务器的分享接口
                Toast.makeText(ReArticleDetailActivity.this, "分享", Toast.LENGTH_SHORT).show();
            }
        });
        like.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //todo 收藏待实现
                Toast.makeText(ReArticleDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
            }
        });
        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ApiManager.addComment(ReArticleDetailActivity.this,mReArticleId,mCommentEdit.getText().toString());
                //清空内容
                mCommentEdit.setText("");
                mCommentEdit.clearFocus();
                //关闭软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean isOpen = imm.isActive();
                if (isOpen) {
                    // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
                    imm.hideSoftInputFromWindow(mCommentEdit.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                //todo 需要刷新webview
            }
        });
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_ra_detail;
    }

}
